package com.qige.homework;

import java.io.*;

/**
 * @Author qige
 * @Date 2024-08-06 20:16
 * @Description
 */
public class homework5 {
    /*
    2.实现字节数组和任何基本类型和引用类型执行的相互转换
    提示：使用ByteArrayInutStream和ByteArrayOutputStream。
     */
    public static void main(String[] args) {
        byte [] bytes = toByteArray(new Integer(123));
        System.out.println(bytes);
        Object object = toObject(bytes);
        System.out.println(object);
    }
    public static byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.flush();
            bytes = baos.toByteArray();
            oos.close();
            baos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return bytes;
    }
    public static Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return obj;
    }
}
